package com.qf.cardlikeboot.service.impl;

import com.google.common.base.Joiner;
import com.qf.cardlikeboot.entity.User;
import com.qf.cardlikeboot.mapper.UserMapper;
import com.qf.cardlikeboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class,readOnly = true,propagation = Propagation.SUPPORTS)
    public User login(String username,String password) {
        User user = userMapper.selectByName(username);
        if (Objects.nonNull(user)){
            if (Objects.equals(user.getPassword(),password)){
                return user;
            }
        }
        return null;
    }

    @Override
    public User likeCard(Integer userId, Integer cardId, Boolean like) {
        User user = userMapper.selectByPrimaryKey(Long.valueOf(userId));
        String liked = user.getLiked();
        if (like){
            liked = StringUtils.isEmpty(liked) ? cardId.toString() : liked + "," + cardId;
        }else {
            List<String> collect = Arrays.stream(liked.split(",")).collect(Collectors.toList());
            collect.remove(cardId.toString());
            liked = Joiner.on(",").join(collect);
        }
        user.setLiked(liked);
        userMapper.updateUser(user);
        return user;
    }
}
